package com.hyt.it.ogt.kq.service.canal.impl;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.hyt.core.enums.DelFlagEnum;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.it.ogt.kq.common.gov.enums.CanalMonitorTableEnum;
import com.hyt.it.ogt.kq.service.admission.IExamineeInfoService;
import com.hyt.it.ogt.kq.service.canal.CanalTableChangeHandlerService;
import com.hyt.it.ogt.kq.service.gov.model.entity.Task;
import com.hyt.it.ogt.kq.service.gov.service.ICandidateService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskService;
import com.hyt.it.ogt.kq.service.model.entity.Candidate;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 考务监听考生信息表变化 服务实现类
 * </p>
 *
 * @author huangwu
 * @since 2022-11-12
 */
@Service
@Slf4j
public class KwCandidateServiceHandlerImpl  implements CanalTableChangeHandlerService {
	
	@Resource
	private ITaskService taskService;
	@Resource
	private IExamineeInfoService examineeInfoService;
	@Resource
	private ICandidateService candidateService;
	
	@Override
	public void dataDetails(List<Column> beforeColumns, List<Column> afterColumns, String dbName, String tableName, EventType eventType, long timestamp) {
		log.debug("[canal][考务][考生信息同步]数据库：{},表名:{},操作类型:{}", dbName, tableName, eventType);
		if (CanalEntry.EventType.INSERT.equals(eventType)) {
			insert(beforeColumns, afterColumns, dbName, tableName, eventType, timestamp);
		} else if (CanalEntry.EventType.DELETE.equals(eventType)) {
			delete(beforeColumns, afterColumns, dbName, tableName, eventType, timestamp);
		} else {
			update(beforeColumns, afterColumns, dbName, tableName, eventType, timestamp);
		}
		log.info("[canal][考务][考生信息同步]操作时间：{}", new Date(timestamp));
	}

	
	@Override
	public void insert(List<Column> beforeColumns, List<Column> afterColumns, String dbName, String tableName, EventType eventType, long timestamp) {
		String taskId = StringUtils.EMPTY;
		for (CanalEntry.Column column : afterColumns) {
			if("task_id".equals(column.getName())) {
				taskId = column.getValue();
			}
		}
		if(StringUtils.isNotEmpty(taskId)) {
			// 如果是新增数据，需要将考生统计变更 +1
			Task task = taskService.getById(taskId);
			if(null != task) {
				Integer candidateCount = task.getCandidateCount();
				task.setCandidateCount(candidateCount + 1);
				taskService.updateById(task);
			}
		}

		// 更新准考证学生信息
		String id = getFieldValue(afterColumns, "id");
		String userId = getFieldValue(afterColumns, "update_by");
		examineeInfoService.insertByGov(candidateService.getById(id), userId);
	}

	@Override
	public void delete(List<Column> beforeColumns, List<Column> afterColumns, String dbName, String tableName, EventType eventType, long timestamp) {
		String taskId = StringUtils.EMPTY;
		for (CanalEntry.Column column : afterColumns) {
			if("task_id".equals(column.getName())) {
				taskId = column.getValue();
			}
		}
		if(StringUtils.isNotEmpty(taskId)) {
			// 如果是新增数据，需要将考生统计变更 +1
			Task task = taskService.getById(taskId);
			if(null != task) {
				Integer candidateCount = task.getCandidateCount();
				task.setCandidateCount(candidateCount - 1);
				taskService.updateById(task);
			}
		}

		// 更新准考证学生信息
		String id = getFieldValue(beforeColumns, "id");
		Candidate candidate = candidateService.getById(id);
		if(null != candidate) {
		    examineeInfoService.deleteByGov(candidate, "");
		}
	}

	@Override
	public void update(List<Column> beforeColumns, List<Column> afterColumns, String dbName, String tableName, EventType eventType, long timestamp) {
	    String taskId = StringUtils.EMPTY;
        for (CanalEntry.Column column : afterColumns) {
            if("task_id".equals(column.getName())) {
                taskId = column.getValue();
            }
        }
        if(StringUtils.isNotEmpty(taskId)) {
            // 如果是新增数据，需要将考生统计变更 +1
            Task task = taskService.getById(taskId);
            if(null != task) {
                String delFlag = getFieldValue(afterColumns, "is_del_flag");
                if(DelFlagEnum.DEL.getCode().toString().equals(delFlag)) {
                    Integer candidateCount = task.getCandidateCount();
                    task.setCandidateCount(candidateCount - 1);
                    taskService.updateById(task);
                }
            }
        }
        
	    String id = getFieldValue(afterColumns, "id");
		String userId = getFieldValue(afterColumns, "update_by");
		Candidate candidate = candidateService.getById(id);
        if(null != candidate) {
            examineeInfoService.updateByGov(candidate, userId);
        }
	}
	
	@Override
	public String getHandleTableName() {
		return CanalMonitorTableEnum.KW_CANDIDATE.getTable();
	}
}
